﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace OAuth2
{

    public static class ApiDHgateHelper
    {

    }


    public static class OperationContext
    {
       


        public ResponeAccessTokenModel getAccessToken(this ApiDHgateHelper api, RequestAccessTokenModel model)
        {
            if (model == null) { return null; }
            StringBuilder strUrl = new StringBuilder();
            strUrl.AppendLine("https://secure.dhgate.com/dop/oauth2/access_token");
            strUrl.AppendLine("?grant_type=" + model.GrantType);
            strUrl.AppendLine("&username=" + model.UserName);
            strUrl.AppendLine("&password=" + model.PassWord);
            strUrl.AppendLine("&client_id=" + model.ClientID);
            strUrl.AppendLine("&client_secret=" + model.ClientSecret);
            strUrl.AppendLine("&scope=" + model.Scope);
            string strData = HttpOperationContext(strUrl.ToString());
            return JsonConvert.DeserializeObject<ResponeAccessTokenModel>(strData);
        }

      
        private string HttpOperationContext(string requestURL)
        {
            HttpWebRequest request =WebRequest.Create(requestURL) as HttpWebRequest;
            request.KeepAlive = false;
            request.AllowAutoRedirect = false;//不允许重定向
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "GET";
            
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return null;
                }
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader streamreader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")))
                    {
                        string s = streamreader.ReadToEnd();
                        return s;
                    }
                }
            }
        }
       
    }
}
